const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  
  console.log('测试云函数被调用')
  console.log('上下文:', wxContext)
  
  try {
    // 测试数据库连接
    console.log('测试数据库连接...')
    const testQuery = await db.collection('users').limit(1).get()
    console.log('数据库连接成功，数据条数:', testQuery.data.length)
    
    return {
      success: true,
      message: '云函数测试成功',
      context: wxContext,
      databaseTest: testQuery.data.length > 0 ? '连接正常' : '无数据',
      timestamp: new Date().toISOString()
    }
  } catch (error) {
    console.error('测试失败:', error)
    return {
      success: false,
      message: '云函数测试失败',
      error: error.message,
      timestamp: new Date().toISOString()
    }
  }
}